import { message } from 'antd';

interface RequestOptions extends RequestInit {
  params?: Record<string, any>;
}

const BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL;

class RequestError extends Error {
  constructor(public status: number, message: string) {
    super(message);
  }
}

export const request = async <T>(endpoint: string, options: RequestOptions = {}): Promise<T> => {
  try {
    const { params, ...restOptions } = options;
    
    const queryString = params
      ? `?${new URLSearchParams(params).toString()}`
      : '';
    
    const response = await fetch(`${BASE_URL}${endpoint}${queryString}`, {
      ...restOptions,
      headers: {
        'Content-Type': 'application/json',
        ...options.headers,
      },
    });

    if (!response.ok) {
      throw new RequestError(response.status, `请求失败: ${response.statusText}`);
    }

    const data = await response.json();
    return data;
  } catch (error) {
    if (error instanceof RequestError) {
      message.error(`请求错误: ${error.message}`);
    } else {
      message.error('网络错误，请稍后重试');
    }
    throw error;
  }
};

export const get = <T>(endpoint: string, params?: Record<string, any>) => {
  return request<T>(endpoint, { method: 'GET', params });
};

export const post = <T>(endpoint: string, data?: any) => {
  return request<T>(endpoint, {
    method: 'POST',
    body: JSON.stringify(data),
  });
};

export const put = <T>(endpoint: string, data?: any) => {
  return request<T>(endpoint, {
    method: 'PUT',
    body: JSON.stringify(data),
  });
};

export const del = <T>(endpoint: string) => {
  return request<T>(endpoint, { method: 'DELETE' });
}; 